<template>
  <div>
    <div class="body_content" :style="{height: client.height-142 + 'px'}">
      <h3 class="page_title">发送广播</h3>
      <el-card class="box-card card_bg asset_form">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="small">
          <el-row>
            <el-col :span="8">
              <el-form-item label="消息标题" prop="title">
                <el-input v-model.trim="ruleForm.title" placeholder="请输入消息标题" size="small"></el-input>
              </el-form-item>
              <el-form-item label="消息内容" prop="content">
                <el-input v-model="ruleForm.content" placeholder="请输入消息内容" type="textarea" :autosize="{ minRows: 4, maxRows: 5}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发布时间" prop="publicDate">
                <el-date-picker v-model="ruleForm.publicDate" placeholder="选择时间" type="datetime" size="small" style="width: 100%;"></el-date-picker>
                </el-date-picker>
              </el-form-item>
              <el-form-item label="接收用户" prop="userIds">
                <Person :clear="clear" @change="selectChange" @clearFinish="clear=false" />
              </el-form-item>
              <el-form-item label="消息类型" required>
                <el-radio-group v-model="ruleForm.type">
                  <!-- <el-radio v-for="messageType in typeList" :label="messageType.configId" :key="messageType.configId">{{messageType.value}}</el-radio>  -->
                  <el-radio v-if="typeList.length > 0" :label="typeList[0].configId" :key="typeList[0].configId">{{typeList[0].value}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="4">

            </el-col>
            <el-col :span="4" class="operate_submit">
              <el-button v-if="roleIdList.includes(79)" type="warning" size="small" @click="createMessage('ruleForm')" class="operate_create">创建</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <h3 class="page_title">历史广播</h3>
      <el-table ref="table" class="fix_top" :data="tableData" style="width: 100%" :max-height="client.height-102-40-420" highlight-current-row
        @cell-mouse-enter="handleCurrentChange" @cell-mouse-leave="removeCurrentChange" :expand-row-keys="expandRowKey" row-key="messageId">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form inline>
              <el-form-item v-for="user in userList" :key="user.user.userId" :label="user.user.userName" style=" margin-right: 0;margin-bottom: 0;width: 50%;font-size:12px;line-height:56px;">
                (
                <span v-if="user.status === 4" style="color:#999">{{ user.statusName }}</span>
                <span v-else-if="user.status === 5 || user.status === 7" style="color:#d9524E">{{ user.statusName }}</span>
                <span v-else-if="user.status === 6" style="color:#5cb95c">{{ user.statusName }}</span>
                )
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" prop="messageId" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="消息标题" prop="title" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="消息内容" prop="content" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="发布时间" prop="publicDate" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="发布者" prop="sendname" show-overflow-tooltip>
        </el-table-column>
        <el-table-column min-width="160">
          <template slot-scope="scope">
            <div class="table_operate" v-if="currentRow === scope.row.messageId">
              <el-button-group>
                <el-button v-if="roleIdList.includes(80)" class="table_operate_btn table_show" @click.native.prevent="detailRol(scope.row)"
                  type="text" size="small">
                  <i class="fa fa-ellipsis-h"></i> 详情
                </el-button>
                <el-button v-if="roleIdList.includes(81)" class="table_operate_btn table_delete" @click.native.prevent="deleteRow(scope.row)"
                  type="text" size="small">
                  <i class="fa fa-trash-o"></i> 移除
                </el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block page_detail">
        <el-pagination @current-change="handlePageCurrentChange" :current-page.sync="pageParam.pageCurrent" :page-size="pageParam.pageSize"
          layout="prev, pager, next, jumper" :total="itemTotal">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    mapState
  } from "vuex";
  import {
    load
  } from "../../lib/utils";
  import {
    baseConfig,
    messageManagement
  } from "../../service/service_zbw.js";
  import {
    formCheck,
    trim,
    dateFormat,
    dataSort
  } from "../../lib/utils";
  import Person from "../../components/deptPerson/chosePerson.vue";
  export default {
    computed: {
      ...mapState({
        client: state => state.client,
        roleIdList: state => state.roleIdList,
      })
    },
    components: {
      Person
    },
    data() {
      //消息标题校验
      const title = (rule, value, callback) => {
        value = trim(value);
        if (!value) {
          return callback(new Error("请输入消息标题"));
        } else if (value.length > 20) {
          return callback(new Error("消息标题不能超过20个字"));
        } else {
          callback();
        }
      };
      //消息内容校验
      const content = (rule, value, callback) => {
        value = trim(value);
        if (!value) {
          return callback(new Error("请输入消息内容"));
        } else if (value.length > 200) {
          return callback(new Error("消息内容不能超过200个字"));
        } else {
          callback();
        }
      };
      //发布时间校验
      const publicDate = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("请选择发布时间"));
        } else {
          callback();
        }
      };
      //接收用户校验
      const userIds = (rule, value, callback) => {
        if (value.length === 0) {
          return callback(new Error("请选择接受用户"));
        } else {
          callback();
        }
      };
      return {
        //清空用户选择
        clear: false,
        //人员列表
        userIdsList: [],
        //消息类型
        typeList: [{
          configId: '',
          value: ''
        }],
        dept: {
          type: "", //create  update  delete 操作类型
          user: {
            userid: 0, //人员Id
            name: "", //人员名称
            department: [], //所在部门id
            position: "", //职位名称
            mobile: "", //电话
            remark: "" //备注
          }
        },
        //新增消息数据
        ruleForm: {
          title: "",
          content: "",
          publicDate: "",
          type: 1,
          userIds: []
        },
        //新增消息校验
        rules: {
          title: [{
              required: true,
              validator: title,
              trigger: "change"
            },
            {
              min: 1,
              max: 60,
              message: '长度不能超过60个字符',
              trigger: 'blur'
            }
          ],
          content: [{
              required: true,
              validator: content,
              trigger: "change"
            },
            {
              min: 1,
              max: 45,
              message: '长度不能超过45个字符',
              trigger: 'blur'
            }
          ],
          publicDate: [{
            type: "date",
            required: true,
            validator: publicDate,
            trigger: "change"
          }],
          userIds: [{
            type: "array",
            required: true,
            validator: userIds,
            trigger: "change"
          }]
        },
        //列表数据
        tableData: [],
        userList: [],
        expandRowKey: [],
        currentRow: "",
        pageParam: {
          pageCurrent: 1,
          pageSize: 20
        },
        itemTotal: 0
      };
    },
    mounted() {
      //获取消息类型
      this.messageTypeList();
      //获取人员列表
      this.getuserIdsList();
      //查询消息列表
      this.messageList();
    },
    methods: {
      /**
       * 获取人员列表
       */
      async getuserIdsList() {
        // let res = await baseConfig.userIdsList();
        let res = {
          success: true,
          obj: [],
          msg: "人员获取成功！"
        };
        for (let i = 0; i < 10; i++) {
          let userIds = {
            id: i,
            name: "人员" + i
          };
          res.obj.push(userIds);
        }
        if (res.success) {
          this.userIdsList = res.obj;
        } else {
          this.userIdsList = [];
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      },
      /**
       * 获取消息类型
       */
      async messageTypeList() {
        let res = await baseConfig.messageTypeList();
        if (res.success) {
          this.typeList = res.obj;
        } else {
          this.typeList = [{
            configId: '',
            value: ''
          }];
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      },

      /**
       * 获取消息列表
       */
      async messageList() {
        let res = await messageManagement.messageList(this.pageParam);
        if (res.success) {
          for (let index = 0; index < res.obj.items.length; index++) {
            res.obj.items[index].publicDate = dateFormat(
              res.obj.items[index].publicDate
            );
          }
          this.itemTotal = res.obj.itemTotal;
          this.tableData = dataSort(res.obj.items, this.pageParam.pageCurrent);
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      },

      /**
       * 新增消息
       */
      async createMessage(formName) {
        this.ruleForm.title = trim(this.ruleForm.title);
        this.ruleForm.content = trim(this.ruleForm.content);
        let flag = formCheck(this, "ruleForm");
        if (flag) {
          let res = await messageManagement.sendMessage(this.ruleForm);
          if (res.success) {
            this.$refs["ruleForm"].resetFields();
            this.clear = true;
            this.$message({
              type: "success",
              message: res.msg
            });
            this.messageList();
          } else {
            this.$message({
              type: "error",
              message: res.msg
            });
          }
        }
      },

      /**
       * 人员选择改变
       */
      selectChange(val) {
        for (let i = 0; i < val.length; i++) {
          this.ruleForm.userIds.push(val[i].userId)
        }
      },

      /**
       * hover表格某一行获取id
       */
      handleCurrentChange(val) {
        //当删除当前行时,val值不存在
        try {
          this.currentRow = val.messageId;
        } catch (error) {
          this.currentRow = "";
        }
      },
      //取消选中
      removeCurrentChange() {
        this.currentRow = "";
      },

      //通过详情按钮控制表格展开或闭合
      rowExpansion(row) {
        this.$refs.table.toggleRowExpansion(row);
      },
      //获取消息详情
      async detailRol(row) {
        if (row.messageId === this.expandRowKey[0]) {
          this.expandRowKey = [];
          return;
        }
        this.expandRowKey = [row.messageId];
        let res = await messageManagement.detailMessage(row.messageId);
        if (res.success) {
          this.userList = res.obj;
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      },
      //删除确认
      deleteRow(row) {
        this.$confirm("您确定要删除“" + row.title + "”消息吗？", "消息删除", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true
          })
          .then(() => {
            this.deleteMessage(row.messageId);
          })
          .catch(() => {});
      },
      //删除请求
      async deleteMessage(messageId) {
        let res = await messageManagement.deleteMessage(messageId);
        if (res.success) {
          this.$message({
            type: "success",
            message: res.msg
          });
          this.messageList();
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      },
      handlePageCurrentChange(val) {
        //查询消息列表
        this.messageList();
      }
    }
  };

</script>

<style scoped>
  .body_content {
    width: 100%;
    background: #fff;
  }

  .card_bg {
    background: #ebebeb !important;
  }

  .table_show,
  .table_show:link,
  .table_show:visited,
  .table_show:hover,
  .table_show:active {
    background: #535953;
    color: #fff;
  }

  .table_delete,
  .table_delete:link,
  .table_delete:visited,
  .table_delete:hover,
  .table_delete:active {
    background: #d9524e;
    color: #fff;
  }

</style>

